package com.l.web.master.system.user;

import com.l.web.WebConstant;
import com.l.web.master.system.role.Role;
import com.l.web.master.system.role.RoleService;
import org.apache.log4j.Logger;
import org.l.qiao.*;
import org.l.qiao.annotation.Privilege;
import org.l.qiao.builder.Field;
import org.l.qiao.util.ClusterUtil;
import com.l.web.util.ControllerSupport;
import org.l.qiao.web.KeyUpdate;
import com.l.web.common.ResponseCode;
import com.l.web.common.ResponseInfo;
import org.l.qiao.web.form.Form;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping(UserController.URI)
public class UserController extends ControllerSupport {

    public static final String URI = WebConstant.MASTER_URI + "/system/user";
    private static final Logger LOGGER = Logger.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Privilege(module = "用户", function = "帐号管理", operation = "查询")
    @RequestMapping("index.do")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        modelMap.put(WebConstant.CONTROLLER_KEY, URI);
        return new ModelAndView(URI + "/index", modelMap);
    }

    @Privilege(module = "用户", function = "帐号管理", operation = "查询")
    @RequestMapping("list.do")
    public ModelAndView list(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        Form form = getForm(request);
        Page page = form.getPage();
        List<Cluster> list = userService.getPageList(page);
        Cluster roles = userService.getRoleMap();
        modelMap.put("list", list);
        modelMap.put("page", page);
        modelMap.put("roles", roles);
        return new ModelAndView(URI + "/list", modelMap);
    }

    @Privilege(module = "用户", function = "帐号管理", operation = "详情")
    @RequestMapping("detail.do")
    public ModelAndView detail(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws IOException {
        Form form = getForm(request);
        String id = form.getString("id");

        if (Validate.check(Validate.OBJECTID, id)) {
            User user = userService.getDetail(id);
            Cluster role = new Cluster();

            if (user.isEmpty()) {
                LOGGER.error("所查看的帐号不存在");
                response.sendError(404);
                return null;
            }

            if (user.containsKey(User.ROLE_ID)) {
                role = userService.getRoleMap(user);
            }

            modelMap.put("user", user);
            modelMap.put("role", role);
            modelMap.put("check", ClusterUtil.getCheck(User.class));
        } else {
            LOGGER.error("非法查看帐号信息：id=" + id);
            response.sendError(404);
            return null;
        }

        return new ModelAndView(URI + "/detail", modelMap);
    }

    @Privilege(module = "用户", function = "帐号管理", operation = "添加")
    @RequestMapping("add.do")
    public ModelAndView add(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        modelMap.put("check", ClusterUtil.getCheck(User.class));

        Field field = new Field();
        field.exclude(Role.LIMIT);
        List roles = roleService.getList(null, field, null);
        modelMap.put("roles", roles);
        return new ModelAndView(URI + "/add", modelMap);
    }

    @Privilege(module = "用户", function = "帐号管理", operation = "添加")
    @RequestMapping("checkUsername.do")
    public void checkUsername(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws IOException {
        String userName = request.getParameter("userName");

        if (Validate.check("^[\\w\\d]{3,20}$", userName)) {
            long count = userService.getCount(userName);
            ResponseInfo rj = new ResponseInfo();
            rj.put("count", count);
            out(response, rj);
        } else {
            LOGGER.error("检查非法用户名：" + userName);
            response.sendError(404);
        }
    }

    @Privilege(module = "用户", function = "帐号管理", operation = "添加")
    @RequestMapping("save.do")
    public void save(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws IOException {
        Form form = getForm(request);
        User user = new User();
        boolean result = form.getCluster(user);
        LOGGER.debug("添加帐号：" + user);

        if (result) {
            int code = userService.save(user);
            ResponseInfo responseInfo = new ResponseInfo(code);

            if (code == ResponseCode.FINISH) {
                responseInfo.put("id", user.getId());
            }

            out(response, responseInfo);
        } else {
            response.sendError(404);
            LOGGER.error("非法添加帐号：" + user);
        }
    }

    @Privilege(module = "用户", function = "帐号管理", operation = "修改")
    @RequestMapping("roles.do")
    public ModelAndView roles(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        List<Cluster> roles = userService.getRoles();
        modelMap.put("roles", roles);
        return new ModelAndView(URI + "/roles", modelMap);
    }

    @Privilege(module = "用户", function = "帐号管理", operation = "修改")
    @RequestMapping("update.do")
    public void update(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws IOException {
        Form form = getForm(request);
        KeyUpdate keyUpdate = form.getKeyUpdate(User.class);
        LOGGER.debug("修改信息信息：" + keyUpdate);

        if (keyUpdate.check()) {
            long code = ResponseCode.FAILURE;

            try {
                code = userService.update(keyUpdate);
            } catch (Exception e) {
                LOGGER.error("修改异常[" + keyUpdate + "]：" + e);
            }

            out(response, code);
        } else {
            LOGGER.error("非法修改：" + keyUpdate);
            response.sendError(404);
        }
    }

}
